package com.cryptape.cita_wallet.activity.bindwallet;

import android.app.Dialog;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;

import com.blankj.utilcode.util.GsonUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.MapUtils;
import com.blankj.utilcode.util.ObjectUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.cryptape.cita_wallet.CytonApplication;
import com.cryptape.cita_wallet.activity.NBaseActivity;
import com.cryptape.cita_wallet.activity.TransactionDetailActivity;
import com.cryptape.cita_wallet.activity.cloudminer.MinerIncomeActivity;
import com.cryptape.cita_wallet.activity.transactionlist.model.TransactionAdapter;
import com.cryptape.cita_wallet.adapter.BindHashRecordAdapter;
import com.cryptape.cita_wallet.bean.BindHashBean;
import com.cryptape.cita_wallet.bean.MiningWithdrawDetailBean;
import com.cryptape.cita_wallet.item.Wallet;
import com.cryptape.cita_wallet.item.transaction.RestTransaction;
import com.cryptape.cita_wallet.net.callback.CommonCallback;
import com.cryptape.cita_wallet.net.request.HttpRequestMode;
import com.cryptape.cita_wallet.net.response.BaseResponse;
import com.cryptape.cita_wallet.util.RSAUtils;
import com.cryptape.cita_wallet.util.db.DBWalletUtil;
import com.cryptape.cita_wallet.view.TitleBar;
import com.cryptape.cita_wallet.view.dialog.ToastDoubleButtonDialog;
import com.cryptape.cita_wallet.view.dialog.listener.OnDialogOKClickListener;
import com.mangoworld.android.R;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;


public class BindHashRecordActivity extends NBaseActivity {

    private TitleBar titleBar;
    private RecyclerView recyclerView;
    private SmartRefreshLayout refreshLayout;

    private BindHashRecordAdapter bindHashRecordAdapter;
    private ToastDoubleButtonDialog toastDoubleButtonDialog;
    private Wallet mWallet;
    private int page = 1;
    private boolean isMoreData = true;
    private List<BindHashBean> hashBeanList = new ArrayList<>();
    private boolean isRefresh = false;

    @Override
    protected int getContentLayout() {
        return R.layout.activity_bind_hash_record;
    }

    @Override
    protected void initView() {
        titleBar = (TitleBar) findViewById(R.id.title);
        recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
        refreshLayout = (SmartRefreshLayout) findViewById(R.id.refreshLayout);
    }

    @Override
    protected void initData() {
        mWallet = DBWalletUtil.getCurrentWallet(this);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(mActivity);
        linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerView.setLayoutManager(linearLayoutManager);
        bindHashRecordAdapter = new BindHashRecordAdapter(this, hashBeanList);
        recyclerView.setAdapter(bindHashRecordAdapter);
    }

    @Override
    protected void initAction() {
        // 开启自动加载功能（非必须）
        refreshLayout.setEnableAutoLoadMore(true);
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull final RefreshLayout refreshLayout) {
                refreshLayout.getLayout().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        isRefresh = true;
                        page = 1;
                        getSaveLog();
                    }
                }, 2000);
            }
        });
        refreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull final RefreshLayout refreshLayout) {
                refreshLayout.getLayout().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        isRefresh = false;
                        if (!isMoreData) {
                            // 将不会再次触发加载更多事件
                            refreshLayout.finishLoadMoreWithNoMoreData();
                            return;
                        }
                        bindHashRecordAdapter.addLoadingView();
                        getSaveLog();
                    }
                }, 2000);
            }
        });
        //触发自动刷新
        refreshLayout.autoRefresh();

        bindHashRecordAdapter.setOnItemClickListener((view, position) -> {
            BindHashBean bindHashBean = hashBeanList.get(position);
            if (bindHashBean.getStatus() == 0) {
                ToastDoubleButtonDialog.getInstance(BindHashRecordActivity.this, getString(R.string.str_unmap_not)).setOnOkClickListener(new OnDialogOKClickListener() {
                    @Override
                    public void onClick(Dialog dialog) {
                        dialog.dismiss();
                        resetSaveLog(bindHashBean.getId() + "");
                    }
                });
            }
        });
    }

    public void getSaveLog() {
        try {
            Map params = MapUtils.newHashMap();
            params.put("address", mWallet.address);
            params.put("limit", "50");
            params.put("page", page + "");
            String jsonData = GsonUtils.toJson(params);
            String content = RSAUtils.encrypt(jsonData);
            HttpRequestMode.getSaveLog(BindHashRecordActivity.this, content, true, new CommonCallback() {
                @Override
                public void onSuccess(Object data, String successMsg, int responseSuccessCode) {
                    if (isRefresh) {
                        bindHashRecordAdapter.removeLoadingView();
                        refreshLayout.finishRefresh();
                        refreshLayout.resetNoMoreData();
                    } else {
                        refreshLayout.setEnableLoadMore(true);
                        refreshLayout.finishLoadMore();
                    }
                    if (data != null) {
                        //explain: 状态码说明: 0已绑定并且转了MGP, 1绑定中, 2需要绑定, 3系统错误判断, 4已绑定但未转MGP
                        LogUtils.dTag("BindMGPWalletActivity==", "checkAddr data = " + data.toString());
                        BaseResponse baseResponse = (BaseResponse) data;
                        if (baseResponse.isSuccess()) {
                            List<BindHashBean> bindHashBeanList = (List<BindHashBean>) baseResponse.getData();
                            if (ObjectUtils.isNotEmpty(bindHashBeanList)) {
                                page++;
                                if (bindHashBeanList.size() < 50) {
                                    isMoreData = false;
                                }
                                hashBeanList.addAll(hashBeanList.size(), bindHashBeanList);
                                bindHashRecordAdapter.refresh(hashBeanList);
                            } else {
                                isMoreData = false;
                            }
                        }
                    }
                }

                @Override
                public void onFailure(String msg, int responseFailCode) {
                    ToastUtils.showLong(msg);
                    if (isRefresh) {
                        refreshLayout.finishRefresh();
                        refreshLayout.resetNoMoreData();
                    } else {
                        refreshLayout.setEnableLoadMore(true);
                        refreshLayout.finishLoadMore();
                    }
                    isMoreData = false;
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void resetSaveLog(String id) {
        try {
            Map params = MapUtils.newHashMap();
            params.put("id", id);
            String jsonData = GsonUtils.toJson(params);
            String content = RSAUtils.encrypt(jsonData);
            HttpRequestMode.resetSaveLog(BindHashRecordActivity.this, content, true, new CommonCallback() {
                @Override
                public void onSuccess(Object data, String successMsg, int responseSuccessCode) {
                    BaseResponse baseResponse = (BaseResponse) data;
                    ToastUtils.showLong(baseResponse.getMessage());
                    finish();
                }

                @Override
                public void onFailure(String msg, int responseFailCode) {
                    ToastUtils.showLong(msg);
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
